<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Post extends CI_Controller {
	public $layout_view = 'layout/default';
	public function add()
	{
		$this->layout->title('Add new post'); // Set page title
		$data['category'] = $this->config->item('categories');
		if(!empty($_POST)){
			$this->load->helper(array('resizeimg', 'upload', 'input'));
			if($_FILES['post_image']['name'] == '' && $_POST['remote_image'] == ''){
				$data['msg']['type'] = 'alert-error';
				$data['msg']['text'] = 'Please choose upload image or fill the remote URL.';
			}
			else{
				// upload file
				if($_FILES['post_image']['name'] != ''){
					unset($_POST['remote_image']);
					$this->load->model('Post_model', 'post');
					if(!$row['post_image'] = $this->post->uploadImage($_FILES['post_image'])){
						$data['msg']['type'] = 'alert-error';
						$data['msg']['text'] = 'Upload failed.';
					}
				}
				// remote image
				else{
					if(!strstr($_POST['remote_image'], 'http://')){
						$_POST['remote_image'] = 'http://'.$_POST['remote_image'];
					}
					if($rs = imageDownloader($_POST['remote_image'])){
						$row['post_image'] = $rs['name'];
						$row['file_checksum'] = $rs['checksum'];
					}
					else{
						$data['msg']['type'] = 'alert-error';
						$data['msg']['text'] = 'Save image failed.';
					}
				}
				if($data['msg']['type'] != 'alert-error'){
					$row = array_merge($row, $_POST);
					array_walk($row, 'cleanValue');
					unset($row['remote_image']);
					$row['post_unique'] = md5(time());
					$sql = $this->db->insert_string('data', $row);
					if($this->db->query($sql)){
						$data['msg']['type'] = 'alert-success';
						$data['msg']['text'] = 'Add new post successful.';
					}
				}
			}
		}
		$this->layout->view('post_add', $data);// Render view and layout
	}
}